package com.contract.service;

import com.contract.common.error.BizException;
import com.contract.common.error.JsonReturnCode;
import com.contract.common.util.FileUtil;
import com.contract.mapper.BizFileMapper;
import com.contract.pojo.bo.BizFile;
import com.contract.pojo.output.JsonResult;
import com.contract.service.common.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 文件service
 *
 * @author liw
 * @version 1.0
 * @date 2022/7/18 14:50
 */
@Service
@Slf4j
public class FileService extends BaseService {

    @Autowired
    private BizFileMapper bizFileMapper;

    /**
     * 删除
     *
     * @param id 数据
     * @return 1
     */
    public JsonResult<Integer> delete(Long id) {
        return JsonResult.success(bizFileMapper.deleteById(id));
    }

    public JsonResult<Long> upload(MultipartFile file) {
        return JsonResult.success(saveFile(file).getId());
    }

    public void download(Long id) {
        BizFile bizFile = bizFileMapper.selectById(id);
        if (bizFile == null) {
            throw new BizException(JsonReturnCode.FILE_NOT_EXIST_ERROR);
        }
        FileUtil.outFile(response(), new File(getFileRootPath() + bizFile.getPath()));
    }

    public BizFile saveFile(MultipartFile file) {
        BizFile bizFile = FileUtil.file2Local(file, getFileRootPath());
        bizFileMapper.insert(bizFile);
        return bizFile;
    }

}
